package com.cdc.webview;

import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView=findViewById(R.id.webView);

        webView.loadUrl("file:///android_asset/bootstrap_sign_in.html");
        WebSettings mSettings = webView.getSettings();
        mSettings.setJavaScriptEnabled(true);//开启javascript
        Js  javaJs=new Js(webView);
        webView.addJavascriptInterface(javaJs,"external");
        webView.setWebViewClient(new Clientweb());
        webView.setWebChromeClient(new ChromeClient());

    }

    private class ChromeClient extends WebChromeClient{
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                    view.getContext());
            builder.setTitle("提示").setMessage(message)
                    .setPositiveButton("确定", null);
            builder.setCancelable(false);
            builder.setIcon(R.mipmap.ic_launcher);
            AlertDialog dialog = builder.create();
            dialog.show();
            result.confirm();
            return true;
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            Uri uri = Uri.parse(message);
            // 通过解析Uri进行逻辑判断，只对预先协商好的协议响应
            if ( uri.getScheme().equals("js")) {
                if (uri.getAuthority().equals("prompt")) {//响应协议上的prompt方法:js://prompt?arg1=111&arg2=222
                    // 获取js传递过来的参数
                    Set<String> collection = uri.getQueryParameterNames();
                    StringBuilder stringBuilder=new StringBuilder();
                    for (String str : collection) {
                        stringBuilder.append(str);
                        stringBuilder.append(":");
                        stringBuilder.append(uri.getQueryParameter(str));
                        stringBuilder.append(",");
                    }
                    //参数result:代表消息框的返回值(输入值)
                    result.confirm("js调用了Android的方法,获取的js传递的参数是:"+stringBuilder.toString().substring(0,stringBuilder.toString().length()-1));
                    //Toast.makeText(view.getContext(),"js调用了Android的方法,获取的js传递的参数是:"+stringBuilder.toString().substring(0,stringBuilder.toString().length()-1),Toast.LENGTH_LONG).show();
                }
                return true;
            }
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return super.onJsConfirm(view, url, message, result);
        }
    }

    private class Clientweb extends WebViewClient{

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Toast.makeText(view.getContext(),request.getUrl().toString(),Toast.LENGTH_LONG).show();
            Uri uri = Uri.parse(request.getUrl().toString());
            // 通过解析Uri进行逻辑判断，只对预先协商好的协议响应
            if ( uri.getScheme().equals("js")) {
                if (uri.getAuthority().equals("method1")) {//响应协议上的method1方法:js://method1?arg1=111&arg2=222
                    // 获取js传递过来的参数
                    Set<String> collection = uri.getQueryParameterNames();
                    StringBuilder stringBuilder=new StringBuilder();
                    for (String str : collection) {
                        stringBuilder.append(str);
                        stringBuilder.append(":");
                        stringBuilder.append(uri.getQueryParameter(str));
                        stringBuilder.append(",");
                    }
                    //Toast.makeText(view.getContext(),"js调用了Android的方法,获取的js传递的参数是:"+stringBuilder.toString().substring(0,stringBuilder.toString().length()-1),Toast.LENGTH_LONG).show();
                }else if(uri.getAuthority().equals("method2")){  //响应协议上的method1方法:js://method2?arg1=111&arg2=222
                    // 获取js传递过来的参数
                    Set<String> collection = uri.getQueryParameterNames();
                    StringBuilder stringBuilder=new StringBuilder();
                    for (String str : collection) {
                        stringBuilder.append(str);
                        stringBuilder.append(":");
                        stringBuilder.append(uri.getQueryParameter(str));
                        stringBuilder.append(",");
                    }
                    //Toast.makeText(view.getContext(),"js调用了Android的方法,获取的js传递的参数是:"+stringBuilder.toString().substring(0,stringBuilder.toString().length()-1),Toast.LENGTH_LONG).show();
                }
                return true;
            }else{
                //点击页面内的链接可以跳转
                //Toast.makeText(view.getContext(),request.getUrl().toString(),Toast.LENGTH_LONG).show();
                view.loadUrl(request.getUrl().toString());
                return true;
            }
        }

        /**
         * 页面加载完成回调的方法
         */
        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
            //JS代码调用一定要在 onPageFinished（） 回调之后才能调用，否则不会调用
            //4.4以下使用此方法  无法获得js的返回值
            view.loadUrl("javascript:callJs(\"Android传递数据给js\");");
            //4.4以上使用此方法，可以获得js的返回值
            view.evaluateJavascript("javascript:callJsByEval(\"Android传递数据给js eval\")", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                    Toast.makeText(view.getContext(),value,Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}
